<template>
  <div>
    <el-table ref="table"
              :data="value"
              row-key="id"
              border
              :span-method="arraySpanMethod"
              :header-cell-style='headerStyle'
              :cell-style='cellStyle'
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              :row-style="rowStyle"
              @cell-click="handleCellClick">
      <el-table-column fixed v-if="!$route.path.includes('/publicReport')"
                       align='center'
                       width="40px">
        <template>
          <i class="dragIcon el-icon-rank"/>
        </template>
      </el-table-column>
      <template v-for='item in columns'>
        <el-table-column v-if='item.fixed'
                         :key='item.id'
                         :prop='item.field'
                         :label='item.headerText'
                         :fixed='item.fixed'
                         :min-width='item.width ? item.width : "120px"'
                         show-overflow-tooltip
                         :align='item.fixed ? "left" : "right"'
                         :filters='item.filter'
                         :filter-method="filterHandler">
          <template slot-scope="scope">
            <div v-if='scope.row.headerName' class="cursor_pointer">
              <div @click="clickHaner(scope.row)">{{scope.row.headerName}}</div>
            </div>
            <div class="user"
                 v-else-if='item.field === "userName"'>
              <div v-if="scope.row.edit"
                   style="display: flex;align-items: center">
                <el-select v-model="scope.row.userId"
                           style="width: 150px">
                  <el-option v-for="item in userList"
                             :key="item.id"
                             :label="item.realName"
                             :value="item.id">
                  </el-option>
                </el-select>
                <i class="el-icon-check rowEdit"
                   @click="saveEdit(scope.row)"></i>
                <i class="el-icon-close rowEdit"
                   @click="cancelEdit(scope.row)"></i>
              </div>
              <div v-else>
                <img v-if='scope.row.headUrl'
                     :src="scope.row.headUrl"
                     :onerror="defaultImg"
                     alt=""><img v-else
                     :src="defaultAvatar"
                     alt="">{{scope.row[item.field]}}
              </div>
            </div>
            <div v-else-if='item.fixed'>
              {{scope.row[item.field]}}
            </div>
            <div v-else>
              {{scope.row[item.field] ? scope.row[item.field].count : ' '}}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-else
                         :key='item.id'
                         :prop='item.field'
                         :label='item.headerText'
                         :min-width='item.width ? item.width : "120px"'
                         show-overflow-tooltip
                         :align='item.fixed ? "left" : "right"'>
          <template slot-scope="scope">
            {{scope.row[item.field] ? scope.row[item.field].count : ' '}}
          </template>
        </el-table-column>
      </template>
    </el-table>
    <score-card-check-in :visible.sync="checkInVisible" :format="format" :currentRow="currentRow" :currentColumn="currentColumn" @change="$emit('change')"></score-card-check-in>
  </div>
</template>

<script>
import scoreCardCheckIn from "@/components/score-card-table/score-card-check-in.vue";
import Sortable from 'sortablejs'
import { cloneDeep } from 'lodash'
import { v4 } from 'uuid'

function exchange (index1, index2, arr) {
  const cloneArrary = cloneDeep(arr)

  arr[index1] = cloneArrary[index2]
  arr[index2] = cloneArrary[index1]
  return arr
}
import defaultAvatar from '../../assets/default_avatar.png'
export default {
  name: 'scoreCard',
  props: ['value', 'columns', 'format'],
  components: {
    scoreCardCheckIn
  },
  data () {
    return {
      defaultAvatar: defaultAvatar,
      headerStyle: {
        background: '#F2F6FC',
        color: '#404040'
      },
      startIndex: null,
      endIndex: null,
      userList: [],
      defaultImg: 'this.src = "'+defaultAvatar+'"',
      currentRow: {},
      currentColumn: {},
      checkInVisible: false
    }
  },
  // updated () {
  //   this.$nextTick(() => {
  //     setDomAttr(this)
  //   })
  // },
  
  computed: {
    currentValue: {
      get () {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        return this.value.sort((pre, next) => pre.sort - next.sort).map((record, index) => ({ ...record, unique: v4() }))
      },
      set (val) {
        const value = val.map((record, index) => ({ ...record, sort: index }))
        this.$emit('input', value)
      }
    }
  },
  created () {
    this.getUserList()
  },
  mounted () {
	  document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.$nextTick(()=>{
      this.dragSort()
    })
  },
  methods: {
    getUserList () {
      const params = {
        status: 1
      }
      this.$interface.schedule.getWorkScheduledUserListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.userList = res.data
        })
        .catch(() => { })
    },
    rowStyle ({ row }) {
      if (row.code === 419 || row.code === 420 || row.code === 421) {
        return {
          filter: 'blur(4px)',
          cursor: 'not-allowed',
          pointerEvents: 'none'
        }
      }
      if(row.headerName) {
        return {
          backgroundColor: '#EEE',
          height: '24px!important'
        }
      }
    },
    saveEdit (row) {
      row.edit = false
      row.originUserId = row.userId
      const user = this._.find(this.userList, (item) => {
        return item.id === row.userId
      })
      row.userName = user.realName
      row.headUrl = user.headUrl
      this.$emit('changeUserName', row)
    },
    cancelEdit (row) {
      row.userId = row.originUserId
      row.edit = false
    },
    handleCellClick (row, column) {
      const columnKey = ['userName', 'kpi', 'currentValue', 'benchMark']
      if (columnKey.includes(column.property)) {
        if (column.property === 'userName') {
          if (row.edit || this.$route.path.includes('/publicReport')) {
            return false
          }
          this.$set(row, 'edit', true)
        }
      } else {
        const cloneRow = this._.cloneDeep(row)
        const fields = cloneRow.Indicators[0].fields
        if (!cloneRow[column.property]) {
          const timezone = this._.find(this.columns, {field: column.property })
          cloneRow.Indicators.unshift({
            id: v4(),
            date: column.property,
            names: null,
            fields: fields,
            gadgetId: cloneRow.id,
            timezone: timezone.timezone
          })
        }
        this.currentRow = cloneRow
        this.currentColumn = column
        this.checkInVisible = true
      }
    },
    updatedTableData () {
      if (this.startIndex === this.endIndex) {
        return false
      }
      const tableData = this.value
      const currentRow = tableData.splice(this.startIndex, 1)[0]
      tableData.splice(this.endIndex, 0, currentRow)
      this.$emit('input', tableData)
    },
    cellStyle ({ row, column }) {
      if(row.headerName) {
        return {
          padding:'5px 0'
        }
      }
      if (column.label === 'User') {
        return {
          padding: 0
        }
      }
      if (row && row[column.property] && row[column.property].style) {
        return row[column.property].style
      }
      return {}
    },
    filterHandler (value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    onMouseDown (event) {
      for (let index = 0; index < event.composedPath().length; index++) {
        const element = event.composedPath()[index]
        if (element.className.includes('el-table__row') && !element.className.includes('el-table__row--level-1')) {
          element.setAttribute('draggable', true)
          return
        }
      }
    },
    onMouseup (event) {
      for (let index = 0; index < event.composedPath().length; index++) {
        const element = event.composedPath()[index]
        if (element.className.includes('el-table__row')) {
          element.setAttribute('draggable', false)
          return
        }
      }
    },
    dragSort () {
      if(this.$route.path.includes('/publicReport')) {
          return false
        }
      const table = this.$refs.table
      // var array = document.getElementsByTagName('tbody')
      var array = table.$el.querySelectorAll('tbody')
      this.sortable = Sortable.create(array[1], {
        animation: 500,
        delay: 0,
        onEnd: ({ newIndex, oldIndex }) => {
          const currRow = this.value.splice(oldIndex, 1)[0]
          this.value.splice(newIndex, 0, currRow)
          this.updatedTableData()
          this.$emit('scoreCardDrop')
        }
      })
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (row.headerName) {
          if (columnIndex > 0) {
          return [1,5]
          }
        }
    },
    clickHaner(row) {
      if(row.headerName) {
        if(this.$route.path.includes('/publicReport')) {
          return false
        }
        this.$emit('openHeaderDialog',row)
      }
    }
  }

}
</script>

<style scoped>
.user {
  display: flex;
  align-items: center;
}
.user img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}
.dragIcon {
  cursor: pointer;
  font-size: 18px;
}
.rowEdit {
  width: 24px;
  height: 24px;
  background: #3dbdb7;
  color: #ffffff;
  border-radius: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 13px;
  cursor: pointer;
}
.bgcrow {
  background-color: #ccc;
}
</style>
